<?php
/**
 * Elgg mycase recommended tags library
 *
 * Action to recommend tags for a good practice title, call from views/default/mycase/form.php
 */

 	
/*
 * Returns an array with labels for a given word in order of relevance
 * $word: word for which to obtain tags
 * $language: Search language (which allows google, eg: es,en, fr)
 * $site: Web, which seeks to find any? (ie wikipedia.org)
 * $numberOfResults: number of labels you want to get 
 * */
 //gatekeeper();
 //action_gatekeeper();

 $word = urldecode(get_input('text'));

 
 echo implode(",",array_keys(tags4Word($word,'en','?',5)));

 
 exit();
 
function tags4Word($word,$language,$site,$numberOfResults){
	$references = array();
	$moreReferences = array();
	$referencesExtra = array ();
	$suggestedTagsExtra = array();
	$numberOfResults = 5;

	$referencesGoogle = getUrls ($word, $language, $site, $numberOfResults);

	$referencesWikipedia = getUrls ($word, $language, 'http://wikipedia.org', 1);

	$referencesScholar = getUrlsFromScholar($word, $language);

	$references = array_merge($references, $referencesWikipedia, $referencesScholar);

	$references= array_unique($references);

	$suggestedTags = getTags(array2UTF8 ($references));

	//If there isn't tag matchs with the whole title, try the title words grouped in pairs in a single search engine (google and 4 search results)
	if(count($suggestedTags)<2){
		$words=explode(' ',$word);
		$i=0;
		while($i<count($words) && isset($words[$i+1])) {					
			$moreReferences = getUrls ($words[$i] . " " . $words[$i+1], $language, $site, 3);
			$referencesWikipedia = getUrls ($words[$i] . " " . $words[$i+1], $language, 'http://wikipedia.org', 2);
			$referencesExtra = array_merge($moreReferences,$referencesWikipedia);
			++$i;
		}
		$suggestedTagsExtra = getTags(array2UTF8 ($referencesExtra));
		$suggestedTagsExtra = array_map("reverse", $suggestedTagsExtra);//ObtainedTags from links obtained by searching for grouped title words are penalized as the worst tags
		
		
	}

	//Still no tag found but there was some effective search -> put the first url as the tag found
	if(count($suggestedTags)==0 && count($suggestedTagsExtra)==0 && count($referencesGoogle)!=0){
		
		$parsedTag= parse_url($referencesGoogle[0]);
		$suggestedTags = array($parsedTag['host'] => 0);



	}

	$suggestedTags = array_merge($suggestedTagsExtra,$suggestedTags);
	arsort($suggestedTags);
	return array_slice( $suggestedTags, 0 , $numberOfResults);
}




/*
 * Auxiliar Functions
 * 
 * */
function array2UTF8(array $array) {
	
    $arrayUTF8 = array();
    foreach($array as $key => $value) {
		
		if(!mb_check_encoding($key, 'UTF-8')){
			$key = utf8_encode($key);
		}
		
		if(is_array($value)){
			$value = array2UTF8($value);
		}

		$arrayUTF8[$key] = $value;
	}
    return $arrayUTF8;
    
  } 
  
function reverse($n){
    return($n -10000);
}

/*
 * Devuelve las etiquetas asociadas a los enlaces (direcciones) que se le pasan como parámetro.
 * 
 * direcciones: Array de urls
 * 
 * */

function getTags($references){

	
	$tags = array();
	$urlMD5="";
	$data="";
	$reply="";
	
	$i=0;
	$nReferences=count($references);

	
	while($i < $nReferences ){
	

		
		$urlMD5 = md5($references[$i]);	
		$data = @file_get_contents("http://feeds.delicious.com/v2/json/urlinfo/" . $urlMD5);	 

		$reply = json_decode($data);
		 
		
		
		// Check if the address exists on delicious
		if($data !="[]"){
			
			// Check if there are tags for a reference
			if(sizeof($reply[0]->top_tags)>0){
					

				foreach (array_keys(get_object_vars($reply[0]->top_tags)) AS $tag){
					

					if(!array_key_exists($tag,$tags)){
						
						$tags[$tag] = $reply[0]->top_tags->$tag;		
							
					}
					// If the tag is in the array, add the number of occurrences 
					else{
						
						$tags[$tag] = $tags[$tag] + $reply[0]->top_tags->$tag;		
						
					}
					
					
				}
			}
		}

	++$i;
	}
	
	return $tags;
}


/*
 * Returns an array with urls from google search
 * $word: search word
 * $language: Search language (which allows google, eg: es,en, fr)
 * $site: Web, which seeks to find any? (ie wikipedia.org)
 * $numberOfResults: number of URLs that you want to get multiples of 4 and a maximum of 64
 * */
function getUrls ($word, $language, $site, $numberOfResults){
	$completedRequest = 0;
	$word = urlencode($word);
	$references = '';
	$urls=array();
	$sesionCurl="";
	$reply="";
	$search="";

	while( $completedRequest < ($numberOfResults/4) ){
		
		$sesionCurl = curl_init();
		curl_setopt($sesionCurl, CURLOPT_URL, 'http://ajax.googleapis.com/ajax/services/search/web?v=1.0&hl='.$language.'&q=site:'. $site .'+'.$word.'&start='. $completedRequest*4 );
		curl_setopt($sesionCurl, CURLOPT_RETURNTRANSFER, 1);
		curl_setopt($sesionCurl, CURLOPT_REFERER, 'http://www.syntax.cwarn23.info/');//CHANGE FOR URL SITE
		$reply = curl_exec($sesionCurl);
		curl_close($sesionCurl);

		$search = json_decode($reply);	

		foreach ($search->responseData->results AS $match) {

			
			$references .= ' ';
			$references .= urldecode($match->url);// Decode url to delicious
			
		}
		++$completedRequest;
	}

	$urls=explode (' ',$references);
	array_shift($urls);
	
	return $urls;
	
}
/*
 * Returns an array with urls from Scholar google search
 * $word: search word
 * $language: Search language (which allows google, eg: es,en, fr)
 * 
 * */
function getUrlsFromScholar($word,$language){

	$word = urlencode($word);
	$data = @file_get_contents('http://scholar.google.com/scholar?q='. $word . '&hl=' . $language . '&btnG=Search&as_sdt=2001&as_sdtp=on' );


	$pattern = "/class=gs[^=]+<a href=\"(http:\/\/[^\"]+)\"[^=\"]+/";


	preg_match_all( $pattern, $data, $references );
	

	return $references[1];
}

?>

